﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public interface IUpdate
{
    void Update();
}

public class UpdateDriver: MonoBehaviour
{
    System.Action _OnUpdate;
    System.Action _OnDestroy;
    public void Init(System.Action delUpdate, System.Action delDestroy)
    {
        _OnUpdate = delUpdate;
        _OnDestroy = delDestroy;
    }

    void Update()
    {
        _OnUpdate();
    }

    void OnDestroy()
    {
        if (_OnDestroy != null)
            _OnDestroy();
    }
}

public class UpdateMgr : IPurge
{
    static UpdateMgr _instance;

    List<IUpdate> s_list;

    static UpdateMgr instance
    {
        get
        {
            if(null == _instance)
            {
                _instance = new UpdateMgr();
                PurgeMgr.Regist(_instance);
            }

            return _instance;
        }
    }

    /// <summary>
    /// 单一实例初始化;
    /// </summary>
    protected UpdateMgr()
    {

    }

	void OnUpdate()
    {
	    for(int i = 0; i < s_list.Count; i++)
        {
            s_list[i].Update();
        }
	}

    void OnDestroy()
    {

    }

    public static void Regist( IUpdate u)
    {
        if (null == instance.s_list)
            instance.s_list = new List<IUpdate>();

        instance.s_list.Add(u);
    }

    public static void Remove(IUpdate u)
    {
        if (null == _instance || null == _instance.s_list)
            return;

        _instance.s_list.Remove(u);
    }

    void IPurge.PrePurge()
    {
        
    }

    void IPurge.Purge()
    {
        if (_instance != null)
        {
            if (s_list != null)
                s_list.Clear();
            _instance = null;
        }
    }
}
